<!DOCTYPE html>
<html>
<head>
    <title>WebSocket Chat</title>
    <meta charset="UTF-8">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.5.0/sockjs.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
    <style>
        body { font-family: sans-serif; }
        .login-container, .chat-container { margin: 20px; padding: 20px; border: 1px solid #eee; border-radius: 8px; }
        .login-container h2, .chat-container h2 { margin-top: 0; }
        .login-container input, .chat-container input, .login-container button, .chat-container button {
            margin-right: 10px; margin-bottom: 10px; padding: 8px; border: 1px solid #ccc; border-radius: 4px;
        }
        .login-container button, .chat-container button {
            background-color: #007bff; color: white; cursor: pointer; border: none;
        }
        .login-container button:hover, .chat-container button:hover { background-color: #0056b3; }
        .chat-container { display: none; } /* 默认隐藏聊天界面 */

        .message-container {
            height: 400px;
            overflow-y: auto;
            border: 1px solid #ccc;
            padding: 10px;
            margin-bottom: 10px;
        }
        .message {
            margin-bottom: 10px;
            padding: 5px;
            border-bottom: 1px solid #eee;
        }
        .message-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 5px;
        }
        .sender {
            font-weight: bold;
        }
        .time {
            color: #666;
            font-size: 0.8em;
        }
        .read-status {
            font-size: 0.7em;
            color: #999;
            margin-left: 5px;
        }
        .my-message {
            text-align: right;
            background-color: #e0e0e0;
        }
        .my-message .sender {
            color: #555;
        }
        .unread-message {
            background-color: #fffacd; /* Light yellow for unread */
        }
    </style>
</head>
<body>
<div id="loginContainer" class="login-container">
    <h2>用户登录</h2>
    <div>
        <input type="text" id="loginUsername" placeholder="用户名 (例如: aa1, wyt)">
        <input type="password" id="loginPassword" placeholder="密码 (例如: 123456789)">
        <button onclick="loginAndConnect()">登录</button>
    </div>
    <p style="color: red;" id="loginError"></p>
</div>

<div id="chatContainer" class="chat-container">
    <h2>WebSocket Chat</h2>
    <p>当前用户: <span id="displayUsername">未登录</span></p>
    <div>
        <input type="text" id="targetUser" placeholder="输入聊天对象的用户名">
        <button onclick="loadHistoryAndSwitchChat()">切换聊天对象</button>
    </div>
    <div>
        <input type="text" id="message" placeholder="输入消息">
        <button onclick="sendMessage()">发送</button>
    </div>
    <div id="messageContainer" class="message-container"></div>
</div>

<script>
    let stompClient = null;
    let currentUser = null;
    let currentTargetUser = null;
    let jwtToken = null;

    document.addEventListener('DOMContentLoaded', (event) => {
        document.getElementById('chatContainer').style.display = 'none';
        document.getElementById('loginContainer').style.display = 'block';
    });

    async function loginAndConnect() {
        const username = document.getElementById('loginUsername').value.trim();
        const password = document.getElementById('loginPassword').value.trim();
        const loginErrorElement = document.getElementById('loginError');
        loginErrorElement.textContent = '';

        if (!username || !password) {
            loginErrorElement.textContent = "请输入用户名和密码。";
            return;
        }

        try {
            const response = await fetch('http://localhost:8080/api/user/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ userName: username, password: password }),
            });

            const data = await response.json();

            let tokenFound = false;

            if (response.ok && data.code === 200) {
                if (data.data && data.data.access_token) {
                    jwtToken = data.data.access_token;
                    tokenFound = true;
                } else if (data.access_token) {
                    jwtToken = data.access_token;
                    tokenFound = true;
                }
            }

            if (tokenFound) {
                currentUser = username;

                document.getElementById('loginContainer').style.display = 'none';
                document.getElementById('chatContainer').style.display = 'block';
                document.getElementById('displayUsername').innerText = currentUser;

                connectWebSocket();
            } else {
                loginErrorElement.textContent = data.message || "登录失败，请检查用户名和密码。";
                console.error("Login failed: Token not found in response data.", data);
            }
        } catch (error) {
            loginErrorElement.textContent = "网络或服务器错误，请稍后再试。";
            console.error("Login error:", error);
        }
    }

    function connectWebSocket() {
        if (!jwtToken || !currentUser) {
            console.error("没有JWT Token或当前用户未设置，无法连接WebSocket。");
            document.getElementById('displayUsername').innerText = '连接失败';
            return;
        }

        const socket = new SockJS('/ws');
        stompClient = Stomp.over(socket);

        stompClient.connect({ 'Authorization': 'Bearer ' + jwtToken }, function(frame) {
            console.log('Connected: ' + frame);
            document.getElementById('displayUsername').innerText = currentUser;

            stompClient.send("/app/chat.join", {}, JSON.stringify({
                'from': currentUser,
                'type': 'JOIN'
            }));

            stompClient.subscribe('/user/queue/messages', function(message) {
                const chatMessage = JSON.parse(message.body);
                console.log("Received message:", chatMessage);

                // 检查消息是否属于当前聊天对象，或者是否是系统消息
                const isForCurrentChat = (chatMessage.type === 'SYSTEM') ||
                    (chatMessage.from === currentTargetUser && chatMessage.to === currentUser) ||
                    (chatMessage.from === currentUser && chatMessage.to === currentTargetUser);

                // 根据消息ID查找是否已存在该消息元素
                const existingMessageElement = document.getElementById('message-' + chatMessage.id);

                if (existingMessageElement) {
                    // 如果消息已存在，且是已读状态更新，则更新其状态
                    const isSelf = chatMessage.from === currentUser;
                    if (chatMessage.readStatus === 'READ' && isSelf && chatMessage.type !== 'SYSTEM') {
                        const readStatusSpan = existingMessageElement.querySelector('.read-status');
                        if (readStatusSpan) {
                            readStatusSpan.textContent = ''; // 清除未读状态文本
                        }
                    }
                } else if (isForCurrentChat) { // 只有是新消息且属于当前聊天时才显示
                    displayMessage(chatMessage, chatMessage.from === currentUser);

                    // 如果消息是发给当前用户的且是未读，则发送已读回执
                    if (chatMessage.to === currentUser && chatMessage.readStatus === 'UNREAD') {
                        sendReadReceipt(chatMessage.from, chatMessage.to);
                    }
                }
            });

            if (currentTargetUser) {
                loadChatHistory();
            }

        }, function(error) {
            console.error('STOMP error ' + error);
            document.getElementById('displayUsername').innerText = '连接失败';
            alert("WebSocket连接失败，请检查后端和网络。");
        });
    }

    function sendMessage() {
        const messageInput = document.getElementById('message');
        const messageContent = messageInput.value.trim();

        if (!messageContent || !currentUser || !currentTargetUser) {
            alert("请输入消息内容，并选择聊天对象。");
            return;
        }

        if (stompClient && stompClient.connected) {
            const chatMessage = {
                from: currentUser,
                to: currentTargetUser,
                content: messageContent,
                type: 'CHAT',
                timestamp: new Date().toISOString() // 发送ISO格式的UTC时间
            };
            stompClient.send("/app/chat.private", {}, JSON.stringify(chatMessage));
            // 消息将通过WebSocket订阅收到后才显示，避免重复显示
            messageInput.value = '';
        } else {
            alert("WebSocket未连接，请先登录。");
        }
    }

    function displayMessage(message, isSelf = false) {
        const messageContainer = document.getElementById('messageContainer');
        const messageElement = document.createElement('div');
        messageElement.classList.add('message');
        messageElement.id = 'message-' + message.id; // 为消息元素设置ID

        if (isSelf) {
            messageElement.classList.add('my-message');
        } else if (message.readStatus === 'UNREAD' && message.to === currentUser) {
            messageElement.classList.add('unread-message');
        }

        let timestampStr = 'Invalid Date';
        if (message.timestamp) {
            try {
                // 尝试解析多种可能的日期字符串格式
                // 数据库返回的可能是 "YYYY-MM-DD HH:mm:ss.SSSSSS"
                let dateString = message.timestamp;
                if (typeof dateString === 'string' && dateString.includes(' ')) {
                    dateString = dateString.replace(' ', 'T'); // 转换为 ISO 8601 兼容格式
                }

                const date = new Date(dateString);

                if (!isNaN(date.getTime())) { // 检查日期是否有效
                    // 格式化为 HH:MM:SS
                    timestampStr = date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
                } else {
                    console.warn("Invalid date received, cannot parse:", message.timestamp);
                }
            } catch (e) {
                console.error("Error parsing timestamp:", message.timestamp, e);
            }
        }

        const readStatusText = (message.readStatus === 'UNREAD' && isSelf && message.type !== 'SYSTEM') ? '(未读)' : '';

        messageElement.innerHTML = `
            <div class="message-header">
                <span class="sender">${message.from === currentUser ? '我' : message.from}</span>
                <span class="time">${timestampStr}</span>
            </div>
            <div class="content">${message.content} <span class="read-status">${readStatusText}</span></div>
        `;
        messageContainer.appendChild(messageElement);
        messageContainer.scrollTop = messageContainer.scrollHeight;
    }

    function loadHistoryAndSwitchChat() {
        const targetUserInputValue = document.getElementById('targetUser').value.trim();
        if (!currentUser) {
            alert("请先登录！");
            return;
        }
        if (!targetUserInputValue) {
            alert("请输入聊天对象的用户名！");
            return;
        }

        currentTargetUser = targetUserInputValue;
        loadChatHistory();
        sendReadReceipt(currentTargetUser, currentUser);
    }

    async function loadChatHistory() {
        if (!currentUser || !currentTargetUser) {
            console.warn("无法加载历史消息：当前用户或目标用户未设置。");
            return;
        }

        const messageContainer = document.getElementById('messageContainer');
        messageContainer.innerHTML = '';

        try {
            const response = await fetch(`/api/chat/history/${currentUser}/${currentTargetUser}`, {
                headers: {
                    'Authorization': 'Bearer ' + jwtToken
                }
            });
            if (!response.ok) {
                throw new Error('网络请求失败 ' + response.statusText);
            }
            const historyMessages = await response.json();
            console.log('Loaded history messages:', historyMessages);
            historyMessages.forEach(msg => {
                const isSelf = msg.from === currentUser;
                displayMessage(msg, isSelf);

                if (msg.to === currentUser && msg.readStatus === 'UNREAD') {
                    sendReadReceipt(msg.from, msg.to);
                }
            });
        } catch (error) {
            console.error('Failed to load chat history:', error);
            alert("加载聊天历史失败：" + error.message);
        }
    }

    function sendReadReceipt(fromUser, toUser) {
        if (stompClient && stompClient.connected) {
            const readReceiptMessage = {
                from: fromUser,
                to: toUser,
                type: 'READ_RECEIPT'
            };
            stompClient.send("/app/chat.read", {}, JSON.stringify(readReceiptMessage));
            console.log(`Sent read receipt for messages from ${fromUser} to ${toUser}`);
        } else {
            console.warn("WebSocket not connected, cannot send read receipt.");
        }
    }

    window.addEventListener('beforeunload', function () {
        if (stompClient && stompClient.connected) {
            stompClient.disconnect(function() {
                console.log("WebSocket disconnected.");
            });
        }
    });

</script>
</body>
</html>